package ca.usherbrooke.mainApp.view.newSimulation;

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import ca.usherbrooke.utils.FormUtility;

public class EquipmentPropertyPanel extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6312325601866354606L;
	private final JTextField imageEquipmentProperty;
	private final JTextField imageEquipmentWidth;
	private final JTextField imageEquipmentHeight;
	private final JTextField color_r;
	private final JTextField color_g;
	private final JTextField color_b;
	private final JTextField imageEquipmentDefault;
	private final JTextField imageEquipmentPropertyName;
	private final JTextField imageEquipmentPropertyId;
	private final JButton selectEquipmentImageProperty;
	private final JButton createEquipmentFileProperty;
	private final JButton addPairNameId;
	private final FormUtility form;
	private final JPanel PropertyPanel;
	private final JPanel parent;
	private final JList equipmentIdList;
	private final JList equipmentNameList;
	private final DefaultListModel equipmentNameListModel;
	private final JPanel listPanel;
	private final DefaultListModel equipmentIdListModel;
	private final JFileChooser fileChooser;
	private Boolean equipmentIsCreated;
	private final String fileSeparator;

	public EquipmentPropertyPanel(JPanel par) {

		fileSeparator = Character.toString(File.separatorChar);
		equipmentIsCreated = false;
		parent = par;
		form = new FormUtility();
		fileChooser = new JFileChooser();
		listPanel = new JPanel();

		PropertyPanel = this;
		PropertyPanel.setLayout(new GridBagLayout());
		PropertyPanel.setBorder(BorderFactory
				.createTitledBorder("Equipment Property"));
		imageEquipmentProperty = new JTextField();
		imageEquipmentWidth = new JTextField();
		imageEquipmentHeight = new JTextField();
		color_r = new JTextField();
		color_g = new JTextField();
		color_b = new JTextField();

		imageEquipmentDefault = new JTextField();
		imageEquipmentPropertyName = new JTextField();
		imageEquipmentPropertyId = new JTextField();
		selectEquipmentImageProperty = new JButton("Select Image");
		createEquipmentFileProperty = new JButton("Create File");
		addPairNameId = new JButton("add pair");

		// list
		equipmentIdList = new JList();
		equipmentIdListModel = new DefaultListModel();
		equipmentIdList.setModel(equipmentIdListModel);

		equipmentNameList = new JList();
		equipmentNameListModel = new DefaultListModel();
		equipmentNameList.setModel(equipmentNameListModel);

		listPanel.add(equipmentNameList);
		listPanel.add(equipmentIdList);

		form.addLabel("Equipment Image: ", PropertyPanel);
		form.addMiddleField(imageEquipmentProperty, PropertyPanel);
		form.addLastField(selectEquipmentImageProperty, PropertyPanel);

		form.addLabel("Equipment Width: ", PropertyPanel);
		form.addMiddleField(imageEquipmentWidth, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Equipment Height: ", PropertyPanel);
		form.addMiddleField(imageEquipmentHeight, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("transparence_color_r: ", PropertyPanel);
		form.addMiddleField(color_r, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("transparence_color_g: ", PropertyPanel);
		form.addMiddleField(color_g, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("transparence_color_b: ", PropertyPanel);
		form.addMiddleField(color_b, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Equipment Default ID: ", PropertyPanel);
		form.addMiddleField(imageEquipmentDefault, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel("Name / ID: ", PropertyPanel);
		form.addMiddleField(imageEquipmentPropertyName, PropertyPanel);
		form.addLastField(imageEquipmentPropertyId, PropertyPanel);

		form.addLabel(addPairNameId, PropertyPanel);
		form.addMiddleField(listPanel, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		form.addLabel(new JLabel(""), PropertyPanel);
		form.addMiddleField(createEquipmentFileProperty, PropertyPanel);
		form.addLastField(new JLabel(""), PropertyPanel);

		// disable creation button
		// createEquipmentFileProperty.setEnabled(false);

		initListener();
	}

	private void initListener() {
		selectEquipmentImageProperty.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				setectEquipmentImage();
			}
		});

		createEquipmentFileProperty.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				createFile();
				removePanelFromParent();
			}
		});

		addPairNameId.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				equipmentIdListModel.addElement(imageEquipmentPropertyId
						.getText());
				equipmentNameListModel.addElement(imageEquipmentPropertyName
						.getText());

			}
		});

	}

	protected void setectEquipmentImage() {
		int returnVal = fileChooser.showOpenDialog(this);
		File file = null;
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile();
			imageEquipmentProperty.setText(file.getAbsolutePath());
		}
	}

	protected void removePanelFromParent() {
		parent.remove(this);
		parent.revalidate();
	}

	protected void createFile() {
		Boolean equipmentImageNameIsSet = false;
		Boolean widthIsSet = true, heightIsSet = true, defalaultIdIsSet = true, pairIdIsSet = true, pairNameIsSet = true, pairIsSet = false, r_colorIsSet = true, g_colorIsSet = true, b_colorIsSet = true;
		double width = -1, height = -1, r_color = -1, g_color = -1, b_color = -1;
		String str = "", namePair = "";
		String nameIdPair = "";
		String imageName = "";
		int index = -1, imageId = -1, defaultId = -1;

		// validate image name
		imageName = imageEquipmentProperty.getText();
		if (!imageName.trim().equalsIgnoreCase(" ")) {
			index = imageName.lastIndexOf(".");
			if (index != -1) {
				equipmentImageNameIsSet = true;
				imageName = imageName.substring(imageName
						.lastIndexOf(fileSeparator) + 1);
			}
		}

		// validate entity width
		try {
			width = Double.parseDouble(imageEquipmentWidth.getText().trim());
		} catch (NumberFormatException e) {
			widthIsSet = false;
		}

		// validate entity height
		try {
			height = Double.parseDouble(imageEquipmentHeight.getText().trim());
		} catch (NumberFormatException e) {
			heightIsSet = false;
		}

		// validate r_color
		try {
			r_color = Double.parseDouble(color_r.getText());
		} catch (NumberFormatException e) {
			r_colorIsSet = false;
		}

		// validate g_color
		try {
			g_color = Double.parseDouble(color_g.getText());
		} catch (NumberFormatException e) {
			g_colorIsSet = false;
		}

		// validate b_color
		try {
			b_color = Double.parseDouble(color_b.getText());
		} catch (NumberFormatException e) {
			b_colorIsSet = false;
		}

		// validate default id
		try {
			defaultId = Integer
					.parseInt(imageEquipmentDefault.getText().trim());
		} catch (NumberFormatException e) {
			defalaultIdIsSet = false;
		}

		// ----------------------to see ----------------------------------------

		// validate name/id
		if (!equipmentIdListModel.isEmpty()
				&& !equipmentNameListModel.isEmpty() && pairNameIsSet
				&& pairIdIsSet) {
			pairIsSet = true;
		}

		// ---------------------------------------------------------------------
		// validate simulation folder name
		String folder = ((NewSimulationPanel) parent).getSimulationName();
		File file = null;

		if (!folder.equalsIgnoreCase(" ")) {

			// validate entries
			if (equipmentImageNameIsSet && widthIsSet && heightIsSet
					&& defalaultIdIsSet && pairIsSet && r_colorIsSet
					&& g_colorIsSet && b_colorIsSet) {

				// get pair name and Id
				int idSize = equipmentIdListModel.getSize();
				int nameSize = equipmentNameListModel.getSize();
				nameIdPair = "";
				for (int i = 0, j = 0; (i < nameSize && j < idSize); i++, j++) {

					pairNameIsSet = false;
					namePair = (String) equipmentNameListModel.get(i);
					if (!namePair.trim().equalsIgnoreCase(" ")) {
						pairNameIsSet = true;
					}

					try {
						pairIdIsSet = true;
						imageId = Integer
								.parseInt((String) equipmentIdListModel.get(j));
					} catch (NumberFormatException e) {
						pairIdIsSet = false;
					}

					if (pairNameIsSet && pairIdIsSet) {
						nameIdPair += namePair + "=" + imageId + "\r\n";
					}

				}// end for

				str = "sprite_sheet_path_key=.." + fileSeparator + "imgs"
						+ fileSeparator + imageName + "\r\n"
						+ "sprite_sheet_entity_width=" + width + "\r\n"
						+ "sprite_sheet_entity_height=" + height + "\r\n"
						+ "transparence_color_r=" + r_color + "\r\n"
						+ "transparence_color_g=" + g_color + "\r\n"
						+ "transparence_color_b=" + b_color + "\r\n"
						+ "default= " + defaultId + "\r\n" + nameIdPair;

				// create directory
				new File(((NewSimulationPanel) parent).getPropertyFolderRoot()
						+ fileSeparator + folder + fileSeparator + "props")
						.mkdirs();

				// create file
				file = new File(
						((NewSimulationPanel) parent).getPropertyFolderRoot()
								+ fileSeparator + folder + fileSeparator
								+ "props" + fileSeparator, "equipment.txt");
				try {
					FileWriter fstream;
					boolean isCeated = file.createNewFile();

					if (isCeated) {
						equipmentIsCreated = true;
						((NewSimulationPanel) parent)
								.setEnableEquipmentPropertyButtton(false);
						fstream = new FileWriter(file);
						BufferedWriter out = new BufferedWriter(fstream);
						out.write(str);
						out.close();
						fstream.close();
					}
				} catch (IOException e) {
					JOptionPane.showMessageDialog(this, e.getMessage(),
							"error", JOptionPane.ERROR_MESSAGE);
				}
			}

		} else {

			// print dialogue simulation is not set
		}
		parent.remove(this);
		parent.revalidate();
	}

	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// The directory is now empty so delete it
		return dir.delete();
	}

	public Boolean getEquipmentIsCreated() {
		return equipmentIsCreated;
	}

	public void setEquipmentIsCreated(Boolean equipmentIsCreated) {
		this.equipmentIsCreated = equipmentIsCreated;
	}
}
